const express = require("express");
const router = express.Router();
const conn = require("../util/sql.js");
const jwt = require("jsonwebtoken");

// 调用应用中间件
router.use(express.urlencoded());

// 登录
router.get("/login", (req, res) => {
    let {
        username,
        password
    } = req.query;
    // console.log(username,password);

    let sql = `select * from user where username="${username}" and password="${password}"`;
    conn.query(sql, (err, result) => {
        if (err) {
            res.status(500).json({
                code: 500,
                msg: "登录失败"
            });
        }
        // console.log(result);
        if (result.length > 0) {
            const token = 'Bearer ' + jwt.sign({
                    name: username
                },
                'gz61', // 加密的密码，要与express-jwt中的验证密码一致
                {
                    expiresIn: 2 * 60 * 60
                } // 过期时间，单位是秒
            )

            res.status(200).json({
                code: 200,
                msg: "登录成功",
                token: token
            });
        } else {
            res.status(201).json({
                code: 201,
                msg: "用户名或密码错误"
            });
        }
    })
})

// 注册
router.post("/register", (req, res) => {
    let {
        username,
        password
    } = req.body;

    let bsql = `select * from user where username="${username}"`;

    conn.query(bsql, (err, result) => {
        if (err) {
            res.status(500).json({
                code: 500,
                msg: "注册失败"
            });
        }
        // console.log(result);
        if (result.length > 0) {
            res.status(201).json({
                code: 201,
                msg: "用户名已存在"
            });
            return;
        }
        let sql = `insert into user(username,password) values ("${username}","${password}")`;

        conn.query(sql, (err, result) => {
            if (err) {
                res.status(500).json({
                    code: 500,
                    msg: "注册失败"
                });
            }
            // console.log(result);
            if (result.affectedRows > 0) {
                res.status(200).json({
                    code: 200,
                    msg: "注册成功"
                });
            }
        })
    })

})

module.exports = router;